import time

from playwright.sync_api import sync_playwright as sp

"""
  1、 pip install playwright
  2、执行playwright install   安装chrome,edge,webkit等，
"""





js = """
Object.defineProperties(navigator, {webdriver:{get:()=>undefined}});
"""
# safari_exec_path = '/System/Volumes/Preboot/Cryptexes/App/System/Applications/Safari.app/Contents/MacOS/Safari'
# a = '/usr/bin/safaridriver'
#
d = sp().start()
# webkit = d.webkit.launch(
#     executable_path=a,
#     headless=False,
#     slow_mo=10,
#     devtools=True
# )
webkit = d.webkit.launch(headless=False,slow_mo=50)
context = webkit.new_context()  # 需要创建一个 context

page = context.new_page()  # 创建一个新的页面

page.add_init_script(js)
# page.wait_for_timeout(10)
# 打开easyjet 并登录
page.goto("https://www.easyjet.com")
page.click('//span[@class="sign-in"]')
page.click('//input[@aria-label="Please enter your email address"]')
page.fill('//input[@aria-label="Please enter your email address"]', "407382770@qq.com")
page.click('//input[@type="password"]')
page.fill('//input[@type="password"]', "yuPf172502!")
page.click("//button[@aria-label='Sign in']")

time.sleep(5)
# 选择航班

page.locator('//h3[text()="Flights"]').click()

isChecked = page.locator("#one-way").get_attribute("aria-checked")
if isChecked == 'false':
    page.locator("//div[@class='ej-checkbox one-way-checkbox']//span[@class='checkbox']").click()

# 选择出发地
page.locator('//input[@aria-label="From Airport"]').click()
page.locator('//input[@aria-label="From Airport"]').clear()
page.locator('//input[@aria-label="From Airport"]').fill("London (All Airports)")
page.keyboard.press("Enter")

# 选择到达地
page.locator('//input[@aria-label="To Airport"]').click()
page.locator('//input[@aria-label="To Airport"]').clear()
page.locator('//input[@aria-label="To Airport"]').fill("Madeira Funchal (FNC)")
page.keyboard.press("Enter")

# 选择起飞日期
date = {
    "01": "January",
    "02": "February",
    "03": "March",
    "04": "April",
    "05": "May",
    "06": "June",
    "07": "July",
    "08": "August",
    "09": "September",
    "10": "October",
    "11": "November",
    "12": "December"
}
departing_time = "2024-05-27"
year, month, day = departing_time.split("-")
page.locator('//span[contains(text(),"Departing")]').click()
# page.wait_for_selector('//h1[@id="drawer-title-routedatepicker"]',timeout=5)
while True:

    if not page.locator(f"//div[@data-tab='Date Calendar Outbound']//h3[text()='{date[month]} {year}']").is_visible():
        page.locator(
            f"//div[@data-tab='Date Calendar Outbound']//h3[text()='{date[month]} {year}']").scroll_into_view_if_needed()
    else:

        break

page.locator(
    f"//div[@data-tab='Date Calendar Outbound']//h3[text()='{date[month]} {year}']/following-sibling::div[1]//div[@data-date='{departing_time}']").click(
    position={"x": 5, "y": 5})

time.sleep(5)
# 选择成人数量[16+]
p_num = 2

page.locator('//input[@name="Adults"]').click()
page.locator('//input[@name="Adults"]').clear()
page.locator('//input[@name="Adults"]').fill(str(p_num))

# 选择儿童数量[2-15]
c_num = 1
page.locator('//input[@name="Children"]').click()
page.locator('//input[@name="Children"]').clear()
page.locator('//input[@name="Children"]').fill(str(c_num))

# 选择婴儿[<2]
infants_num = 0
# page.locator('//input[@name="Infants"]').click()
# page.locator('//input[@name="Infants"]').clear()
# page.locator('//input[@name="Infants"]').fill(str(c_num))

# 点击显示航班
page.focus('//button[@data-ej-gtm="searchpod|searchFlightsButton"]')
page.locator('//button[@data-ej-gtm="searchpod|searchFlightsButton"]').click()
time.sleep(5)

# 判断是否有【继续】弹窗，
if infants_num>0:
    if page.locator('//div[@class="message-drawer ej-text ej-text-dark"]//button').is_visible():
        page.locator('//div[@class="message-drawer ej-text ej-text-dark"]//button').click()

    # time.sleep(5)


def switch_to_page(ctx, url=None):
    """切换到指定url 的 标签页"""
    for item_page in ctx.pages:
        if url:
            if url in item_page.url:
                # 激活当前选项卡
                item_page.bring_to_front()
                return item_page
    else:
        print("not found url")


page = switch_to_page(context, "https://www.easyjet.com/en/buy/flights?isOneWay=on&pid=www.easyjet.com")

while True:
    time.sleep(1)
    if page.locator('//button[@id="ensCloseBanner"]').is_visible():
        break

# choose [accept all cookies]
page.wait_for_selector('//button[@id="ensCloseBanner"]', state="visible", timeout=10000).click()


time.sleep(5)
# 选择票价
t_price = '£132.99'
p_parent = f'//div[@class="flight-grid-slider"]/div[2]//span[@class="access-hidden" and contains(text(), "{t_price}")]/parent::span'
page.locator(p_parent).click()
# 点击continue
time.sleep(3)
if page.locator('//div[@class="centered-container"]//button[@aria-label="Continue"]').is_visible():
    page.locator('//div[@class="centered-container"]//button[@aria-label="Continue"]').click()

time.sleep(2)
page.locator('//div[@class="fare-card__footer"]//button[contains(text(),"Continue with Standard fare")]').click()
# time.sleep(3)

# 跳过选择座位
page.locator('//div[@class="helping-hand"]//button[@aria-label="Skip seats page"]').click()

time.sleep(3)
if page.locator('//h1[contains(text(),"No seats selected, are you sure")]').is_visible():
    page.locator('//button[contains(text(),"Skip seat selection")]').click()

# 跳过添加bag
time.sleep(3)
page \
    .wait_for_selector('//div[@class="helping-hand"]//button[@aria-label="Skip cabin bags page"]',
                       state="visible",
                       timeout=10000) \
    .click()

page \
    .wait_for_selector('//button[@data-ej-gtm="button|addALargeCabinBagDrawer|no"]',
                       state="visible",
                       timeout=10000) \
    .click()

time.sleep(3)

# 添加luggage
bag_15 = 1
bag_23 = 1
page.locator('//input[@aria-label="Add a 15kg bag" and @alt="plus button"]').wait_for(state="visible",timeout=10000)
if bag_15 >= 1:
    for _ in range(bag_15):
        page.locator('//input[@aria-label="Add a 15kg bag" and @alt="plus button"]').click()
        time.sleep(1)

if bag_23 >= 1:
    for _ in range(bag_23):
        page.locator('//input[@aria-label="Add a 23kg bag" and @alt="plus button"]').click()
        time.sleep(1)


page.wait_for_selector('//div[@class="centered-container"]//button[@aria-label="Continue"]',state="visible",timeout=10000).click()
time.sleep(3)

#跳过car 选择
page.wait_for_selector(
    '//div[@class="centered-container"]//button[@aria-label="Skip car rental page"]',
    state="visible",
    timeout=10000).click()
# 跳过 Food and Drink Vouchers
page.wait_for_selector(
    '//div[@class="centered-container"]//button[@aria-label="Skip Eat.Drink.Shop vouchers page"]',
    state="visible",
    timeout=10000).click()


# 跳过保险
page.wait_for_selector(
    '//div[@class="centered-container"]//button[@aria-label="Skip travel insurance page"]',
    state='visible',
    timeout=10000).click()

# ##  Now tell us who's flying

# reason for travel
page.wait_for_selector('//input[@name="reasonForTravel-2"]',state="visible",timeout=10000).click()

# Passenger names

passengers = [{"title": 'Mr', "first_name": 'li', "last_name": 'xiaoming', "age": '18+'},
              {"title": 'Ms', "first_name": 'li', "last_name": 'xh', "age": '18+'}]
if (pl := len(passengers)) > 0:
    for i in range(1, pl + 1):
        page.locator(f'#title-dropdown-adult-{i}').select_option(passengers[i - 1]['title'])
        page.locator(f'#firstname-textbox-adult-{i}').fill(passengers[i - 1]['first_name'])
        page.locator(f'#lastname-textbox-adult-{i}').fill(passengers[i - 1]['last_name'])
        page.locator(f'#age-dropdown-adult-{i}').select_option(passengers[i - 1]['age'])

# 选择儿童
childs = [{"title": 'Mr', "first_name": 'li', "last_name": 'sf', "age": '12'}]
if (cl := len(childs)) > 0:
    for i in range(1, cl + 1):
        page.locator(f'#title-dropdown-child-{i}').select_option(childs[i - 1]['title'])
        page.locator(f'#firstname-textbox-child-{i}').fill(childs[i - 1]['first_name'])
        page.locator(f'#lastname-textbox-child-{i}').fill(childs[i - 1]['last_name'])
        page.locator(f'#age-dropdown-child-{i}').select_option(childs[i - 1]['age'])

# whether you have travel insurance
time.sleep(2)
page.locator('//form[@name="InsuranceNudgeForm"]//input[@name="has-insurance-yes"]').click()
time.sleep(1)
# 点击continue
page \
    .locator('//div[@class="below-section"]//button[@aria-label="Save changes to this section and continue"]') \
    .click()

page.wait_for_selector('//label[@for="payment-page-terms-checkbox"]//span[@class="checkbox"]',state="visible",timeout=10000).click()

# 点击apple pay
page.locator('//button[@title="Pay with Apple Pay"]').click()